﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LogFileParser
{
    public class LogFileItem
    {
        private Dictionary<string, string> _values;
        private List<string> _fieldNames;
        public LogFileItem()
        {
            _values = new Dictionary<string, string>();
            _fieldNames = new List<string>();
        }

        public LogFileItem(LogFileItem parent):this()
        {
            foreach (string field in parent.Values.Keys)
            {
                this[field] = field;
            }
        }

        public string this[string name]
        {
            get
            {
                if (_values.ContainsKey(name))
                {
                    return _values[name];
                }
                else
                {
                    throw(new ArgumentOutOfRangeException("No value with name: " + name + " was found."));
                }
            }
            set
            {
                if (_values.ContainsKey(name))
                {
                    throw (new ArgumentOutOfRangeException("Value with name: " + name + " already exists."));
                }
                else
                {
                    _values.Add(name, string.Empty);
                    FieldNames.Add(name);
                }
            }
        }

        public void SetValue(string name, string value)
        {
            if (_values.ContainsKey(name))
            {
                _values.Remove(name);
                _values.Add(name, value);
            }
            else
            {
                throw (new ArgumentOutOfRangeException("No value with name: " + name + " was found."));
            }
        }

        public string GetValue(string name)
        {
            if (_values.ContainsKey(name))
            {
                return _values[name];
            }
            else
            {
                throw (new ArgumentOutOfRangeException("No value with name: " + name + " was found."));
            }
        }

        public object[] ToArray()
        {
            List<string> lvalues = new List<string>();

            foreach (string field in this.FieldNames)
            {
                lvalues.Add(this[field]);
            }

            return lvalues.ToArray();
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            foreach (string fieldname in FieldNames)
            {
                sb.AppendLine(fieldname + ": " + this[fieldname]);
            }
            return sb.ToString();
        }
        public Dictionary<string,string> Values
        {
            get { return _values; }
        }

        public List<string> FieldNames
        {
            get { return _fieldNames; }
        }
    }
}
